//
//  QRCodeScanController.m
//  原生二维码扫描
//
//  Created by zxy on 2018/4/19.
//  Copyright © 2018年 zssh. All rights reserved.
//

#import "QRCodeScanController.h"
#import <AVFoundation/AVFoundation.h>
#import "POP.h"
#import "Masonry.h"
#import "UIView+XMGExtension.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface QRCodeScanController ()<AVCaptureMetadataOutputObjectsDelegate>
//扫描框
@property(nonatomic,strong)UIView *view_bg;
//扫描线图片
@property(nonatomic,strong)UIImageView *lineImgView;
//提示语
@property(nonatomic,strong)UILabel *lab_word;

//采集的设备
@property(nonatomic,strong)AVCaptureDevice *device;
//设备的输入
@property(nonatomic,strong)AVCaptureDeviceInput *input;
//输出
@property(nonatomic,strong)AVCaptureMetadataOutput *output;
//采集流
@property(nonatomic,strong)AVCaptureSession *session;
//窗口
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic, strong) NSTimer * timer;
@end

@implementation QRCodeScanController


- (UIView *)view_bg {
    
    if (!_view_bg) {
        
        _view_bg = [[UIView alloc] init];
        
        _view_bg.layer.borderColor = [UIColor lightGrayColor].CGColor;
        
        _view_bg.layer.borderWidth = 1;
        _view_bg.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.2];
    }
    
    return _view_bg;
}

-(UIImageView *)lineImgView{
    if(!_lineImgView){
        
        _lineImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,0.7*SCREEN_WIDTH, 12)];
        _lineImgView.image = [UIImage imageNamed:@"QRCodeScanLine"];
         //起点
        _lineImgView.layer.position = CGPointMake(0, 0);
        //定位点
        _lineImgView.layer.anchorPoint = CGPointMake(0, 0);
        
    }
    return _lineImgView;
}

- (UILabel *)lab_word {
    
    if (!_lab_word) {
        
        _lab_word = [[UILabel alloc] init];
        
        _lab_word.textAlignment = NSTextAlignmentCenter;
        
        _lab_word.textColor = [UIColor whiteColor];
        
        _lab_word.font = [UIFont systemFontOfSize:14];
        
        _lab_word.text = @"将二维码/条码放入框内，即可进行扫描";
    }
    
    return _lab_word;
}

- (NSTimer *)timer {
    
    if (!_timer) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(scanLineMove) userInfo:nil repeats:YES];
        
        //立即触发该定时器
        [_timer fire];
    }
    
    return _timer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"二维码扫描";
    
    [self startScan];
}

#pragma mark -开始扫描
-(void)startScan{
    // Device 实例化设备   //获取摄像设备
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input 设备输入     //创建输入流
    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
    
    // Output 设备的输出  //创建输出流
    _output = [[AVCaptureMetadataOutput alloc]init];
    
    //设置代理   在主线程里刷新
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session         //初始化链接对象
    _session = [[AVCaptureSession alloc]init];
    
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    // 二维码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode,AVMetadataObjectTypeInterleaved2of5Code,AVMetadataObjectTypeITF14Code,AVMetadataObjectTypeDataMatrixCode];
    
    // Preview 扫描窗口设置
    _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    _previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    
    //设置扫描的范围，假如屏幕宽为width，屏幕高为height，下面参数含义为：
    //0.15意思为距离屏幕左右距离各为0.15*width；
    //0.25意思为距离屏幕上下距离各为0.25*height;
    //0.7意思为扫描横向范围为0.7*width;
    //0.5意思为扫描纵向范围为0.5*height;

    _output.rectOfInterest = CGRectMake(0.1, 0.25, 0.8, 0.5);
    
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    
    //添加框和线
    [self addSubviews];
    
    [self makeConstraintsForUI];
    
    // Start 开始扫描   //开始捕获
    [_session startRunning];
    
    [self.timer setFireDate:[NSDate distantPast]];
}

#pragma mark -添加框和线
-(void)addSubviews{
    [self.view addSubview:self.view_bg];
    
    [self.view addSubview:self.lab_word];
    
    [_view_bg addSubview:self.lineImgView];
}

#pragma mark -扫描区域UI界面约束
-(void)makeConstraintsForUI{
    
    [_view_bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(0.8*SCREEN_WIDTH, 0.5*(SCREEN_HEIGHT - 64)));
        make.left.mas_equalTo(@(0.1*SCREEN_WIDTH));
        make.top.mas_equalTo(@(0.25*(SCREEN_HEIGHT - 64) - 30));
    }];
    
    [_lab_word mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 20));
        make.left.mas_equalTo(@0);
        make.top.equalTo(_view_bg.mas_bottom).with.offset(20);
    }];
}


#pragma mark -定时器方法-控制线条移动
-(void)scanLineMove{
    POPBasicAnimation *animation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerPosition];
    animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 0.5*(SCREEN_HEIGHT - 64)-8)];
    animation.duration = 2;
    [self.lineImgView.layer pop_addAnimation:animation forKey:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_timer setFireDate:[NSDate distantFuture]];
    _timer = NULL;
}

@end
